package wxapp

import (
	"encoding/json"
	"huling/utils/results"
	utils "huling/utils/tool"
	"io/ioutil"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gohouse/gorose/v2"
)

// 获取编辑名片信息
func GetCard(context *gin.Context) {
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	//获取样式
	hlist, _ := DB().Table("wxapp_tpl").Where("accountID", user.Accountid).Where("type", 0).Order("id desc").Get()
	slist, _ := DB().Table("wxapp_tpl").Where("accountID", user.Accountid).Where("type", 1).Order("id desc").Get()
	//获取用户
	data, err := DB().Table("wxapp_user").Where("id", user.ID).Fields("id,avatar,name,nickname,province,city,mobile,email,company,personal_content,company_content,weixin,wx_qrcode,address,tplid,position,personal_content_show,company_content_show,wxacode").First()
	if err == nil {
		if data["address"] == "" && data["province"] != "" {
			data["address"] = data["province"].(string) + " " + data["city"].(string)
		}
		if data["name"] == "" {
			data["name"] = data["nickname"]
		}
		rooturl, _ := DB().Table("common_config").Where("keyname", "rooturl").Value("keyvalue")
		if hlist == nil {
			hlist = make([]gorose.Data, 0)
		} else {
			for _, val := range hlist {
				if val["image"] != "" {
					val["image"] = rooturl.(string) + val["image"].(string)
				}
			}
		}
		if slist == nil {
			slist = make([]gorose.Data, 0)
		} else {
			for _, val := range slist {
				if val["image"] != "" {
					val["image"] = rooturl.(string) + val["image"].(string)
				}
			}
		}
		//获取样式
		styledata, _ := DB().Table("wxapp_tpl").Where("id", data["tplid"]).OrWhere("dfselect", 1).First()
		if styledata != nil && styledata["image"] != "" {
			styledata["image"] = rooturl.(string) + styledata["image"].(string)
		}
		//获取自定义背景
		user_tpl_image, _ := DB().Table("wxapp_user_tpl").Where("uid", user.ID).Where("tplid", data["tplid"]).Value("image")
		if user_tpl_image != nil && user_tpl_image != "" {
			styledata["image"] = rooturl.(string) + user_tpl_image.(string)
			styledata["bgtype"] = 1
		}
		results.Success(context, "获取编辑名片信息", map[string]interface{}{
			"data":    data,
			"style":   styledata,
			"tpllist": map[string]interface{}{"hlist": hlist, "slist": slist}}, nil)
	} else {
		results.Failed(context, "获取编辑名片信息失败", err)
	}
}

// 保存卡信息
func SaveCard(context *gin.Context) {
	//获取post传过来的data
	body, _ := ioutil.ReadAll(context.Request.Body)
	var parameter map[string]interface{}
	_ = json.Unmarshal(body, &parameter)
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	if _, ok := parameter["upbg"]; ok { //添加自定义背景
		b, _ := json.Marshal(parameter["upbg"])
		var mjson map[string]interface{}
		_ = json.Unmarshal(b, &mjson)
		utplid, _ := DB().Table("wxapp_user_tpl").Where("uid", user.ID).Where("tplid", mjson["tplid"]).Value("id")
		if utplid != nil {
			DB().Table("wxapp_user_tpl").Data(mjson).Where("id", user.ID).Update()
		} else {
			mjson["uid"] = user.ID
			DB().Table("wxapp_user_tpl").Data(mjson).Insert()
		}
		delete(parameter, "upbg") //删除背景图
	} else if parameter["ifclaearbg"] == true {
		DB().Table("wxapp_user_tpl").Where("uid", user.ID).Delete()
	}
	delete(parameter, "ifclaearbg")
	res, err := DB().Table("wxapp_user").
		Data(parameter).
		Where("id", user.ID).
		Update()
	if err != nil {
		results.Failed(context, "更新失败", err)
	} else {
		results.Success(context, "更新成功！", res, nil)
	}
}

// 获取名片夹列表
func FolderList(context *gin.Context) {
	//当前用户
	keyword := context.DefaultQuery("keyword", "")
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	MDB := DB().Table("wxapp_card_folder").Join("wxapp_user", "wxapp_card_folder.card_uid", "=", "wxapp_user.id").Where("add_uid", user.ID)
	if keyword != "" {
		MDB.Where("name", "like", "%"+keyword+"%")
	}
	list, err := MDB.Fields("wxapp_card_folder.id as folder_id,visit_id,folder_time,card_uid,name,avatar,company,position").Get()
	if err != nil {
		results.Failed(context, "获取名片夹列表失败", err)
	} else {
		if list == nil {
			list = make([]gorose.Data, 0)
		} else {
			for _, v := range list {
				v["folder_time"] = TimeToStr(v["folder_time"].(int64), "Y")
			}
		}
		results.Success(context, "获取名片夹列表", list, nil)
	}
	// //获取该用户所以名片
	// card_uids, _ := DB().Table("wxapp_card_folder").Where("uid", user.ID).Pluck("card_uid")
	// var zero int = 0
	// if card_uids == nil || len(card_uids.([]interface{})) == zero {
	// 	results.Success(context, "获取名片夹列表！", make([]gorose.Data, 0), nil)
	// } else {
	// 	MDB := DB().Table("wxapp_user")
	// 	if keyword != "" {
	// 		MDB.Where("name", "like", "%"+keyword+"%")
	// 	}
	// 	cardlist, err := MDB.WhereIn("id", card_uids.([]interface{})).Order("id desc").Get()
	// 	if err != nil {
	// 		results.Failed(context, "获取名片夹列表失败!", card_uids)
	// 	} else {
	// 		if cardlist == nil {
	// 			cardlist = make([]gorose.Data, 0)
	// 		}
	// 		results.Success(context, "获取名片夹列表！", cardlist, nil)
	// 	}
	// }
}

// 获取最近访问列表
func VisitList(context *gin.Context) {
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	//获取post传过来的data
	// list, err := DB().Table("wxapp_visit a").LeftJoin("wxapp_user b on a.visit_uid = b.id").Where("card_id", user.ID).
	// 	Fields("card_id,visit_uid,visit_time,issave,name,avatar,company,position").Get()
	list, err := DB().Table("wxapp_visit").Join("wxapp_user", "wxapp_visit.visit_uid", "=", "wxapp_user.id").Where("card_id", user.ID).
		Fields("wxapp_visit.id as visit_id,card_id,visit_uid,visit_time,issave,name,avatar,company,position").Get()
	if err != nil {
		results.Failed(context, "获取最近访问列表失败", err)
	} else {
		if list == nil {
			list = make([]gorose.Data, 0)
		}
		results.Success(context, "获取最近访问列表", list, nil)
	}
}

// 获取名片协议
func GetAgreement(context *gin.Context) {
	content, err := DB().Table("client_article_manage").Where("type_key", "cardagreement").Fields("id,title,content").First()
	if err != nil {
		results.Failed(context, "获取名片协议失败", err)
	} else {
		results.Success(context, "获取名片协议", content, nil)
	}
}

// 添加卡片访问记录
func AddVisitRecode(context *gin.Context) {
	//获取post传过来的data
	body, _ := ioutil.ReadAll(context.Request.Body)
	var parameter map[string]interface{}
	_ = json.Unmarshal(body, &parameter)
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	parameter["visit_uid"] = user.ID
	//添加访问记录
	vdata, _ := DB().Table("wxapp_visit").Where("card_id", parameter["card_id"]).Where("visit_uid", parameter["visit_uid"]).Value("id")
	if vdata == nil {
		parameter["visit_time"] = time.Now().Unix()
		addId, err := DB().Table("wxapp_visit").Data(parameter).InsertGetId()
		if err != nil {
			results.Failed(context, "添加失败", err)
		} else {
			//直接包对方添加到自己名片夹
			folderdata, _ := DB().Table("wxapp_card_folder").Where("card_uid", parameter["card_id"]).Where("add_uid", parameter["visit_uid"]).Value("id")
			if folderdata == nil { //添加到名片夹
				DB().Table("wxapp_card_folder").Data(map[string]interface{}{
					"add_uid":     parameter["visit_uid"],
					"card_uid":    parameter["card_id"],
					"visit_id":    addId,
					"folder_time": time.Now().Unix(),
				}).Insert()
			}
			results.Success(context, "添加成功！", addId, nil)
		}
	} else {
		results.Success(context, "已添加", vdata, nil)
	}
}
